package com.goudan.rabbitmq.manager.impl;

import com.goudan.rabbitmq.constant.QueueDefinition;
import com.goudan.rabbitmq.manager.EventDispatcher;
import com.goudan.rabbitmq.message.MsgData;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Service("eventDispatcher")
public class EventDispatcherImpl implements EventDispatcher {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${spring.application.name}")
    private String appId;

    @Override
    public void eventFanoutDispatch(MsgData<?> msgData, Integer delay) {
        // 回调用到
        final String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);
        rabbitTemplate.convertAndSend(QueueDefinition.LGD_DELAYED_EXCHANGE,
                QueueDefinition.LGD_DELAYED_ROUTING_KEY, msgData.toJson(), message -> {
                    message.getMessageProperties().setMessageId(messageId);
                    message.getMessageProperties().setTimestamp(new Date());
                    message.getMessageProperties().setAppId(appId);
                    message.getMessageProperties().setDelay(delay);
                    return message;
                }, correlationData);
    }

    @Override
    public void eventFanoutDispatch(MsgData<?> msgData) {
        // 回调用到
        final String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);
        rabbitTemplate.convertAndSend(QueueDefinition.LGD_FANOUT_EXCHANGE, "", msgData.toJson(), message -> {
            message.getMessageProperties().setMessageId(messageId);
            message.getMessageProperties().setTimestamp(new Date());
            message.getMessageProperties().setAppId(appId);
            return message;
        }, correlationData);
    }

    @Override
    public void eventDispatchWithKey(MsgData<?> msgData, String routingKey) {
        final String messageId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData(messageId);
        rabbitTemplate.convertAndSend(QueueDefinition.LGD_DIRECT_EXCHANGE, routingKey, msgData.toJson(), message -> {
            message.getMessageProperties().setMessageId(messageId);
            message.getMessageProperties().setTimestamp(new Date());
            message.getMessageProperties().setAppId(appId);
            return message;
        }, correlationData);
    }
}
